package cn.nubia.admin.common.mybatis.bean;

import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * User: wangj
 * Date: 13-11-15
 * Time: 下午6:20
 */
public class Query<T> implements Serializable {
    public static Map<String, String> MYSQL_SPECIAL_STR = new HashMap<String, String>();

    public final static String PARAM_NAME = "paramList";
    /**
     * 条件语句
     */
    private List<QueryParam> paramList = new ArrayList<QueryParam>();

    public static final int PARAM_BETWEEN = 1;

    public static final int PARAM_EQ = 2;

    public static final int PARAM_LIKE = 3;

    public static final int PARAM_IN = 4;

    public static final int PARAM_GT = 5;

    public static final int PARAM_LT = 6;

    public static final int PARAM_SUB_QUERY_IN = 7;

    public static final int PARAM_SUB_QUERY_LIKE = 8;
    public static final int PARAM_NOT_IN = 9;
    public static final int PARAM_NOT_EQ = 10;
    static {
        MYSQL_SPECIAL_STR.put("\\", "\\\\");

        MYSQL_SPECIAL_STR.put("%", "\\%");
        MYSQL_SPECIAL_STR.put("_", "\\_");
    }


    private Class<T> type;


    Integer pageNo;

    Integer pageSize;

    List<String> includeField = new ArrayList<String>();

    Map<String, DBOrder> orders = new LinkedHashMap<String, DBOrder>();


    public Query(Class<T> type) {
        this.type = type;
    }

    /**
     * 添加in查询
     */
    public Query addIn(String field, List<Integer> list) {
        if (list == null || list.size() == 0) {
            return this;
        }
        paramList.add(new QueryParam(field, list, PARAM_IN));
        return this;
    }
    /**
     * 添加not in查询
     */
    public Query addNotIn(String field, List<Integer> list) {
        if (list == null || list.size() == 0) {
            return this;
        }
        paramList.add(new QueryParam(field, list, PARAM_NOT_IN));
        return this;
    }
    /**
     * 添加in类型子查询语句
     *
     * @param field  域名
     * @param subSql 子查询语句
     * @param datas  子查询条件参数
     * @return
     */
    public Query addSubIn(String field, String subSql, Object... datas) {
        List<Object> list = new ArrayList<Object>();
        Collections.addAll(list, datas);

        paramList.add(new QueryParam(field, subSql, PARAM_SUB_QUERY_IN, list));
        return this;
    }


    /**
     * 添加in类型子查询语句
     *
     * @param field  域名
     * @param subSql 子查询语句
     * @param datas  子查询条件参数
     * @return
     */
    public Query addSubLike(String field, String subSql, Object... datas) {
        List<Object> list = new ArrayList<Object>();
        Collections.addAll(list, datas);
        paramList.add(new QueryParam(field, subSql, PARAM_SUB_QUERY_LIKE, list));
        return this;
    }


    /**
     * 添加in查询
     */
    public Query addInUseString(String field, String... list) {
        if (list == null || list.length == 0) {
            return this;
        }
        List<Integer> intList = new ArrayList<Integer>();
        for (int i = 0; i < list.length; i++) {
            if (list[i] != null && list[i].length() > 0)
                intList.add(Integer.parseInt(list[i]));
        }
        paramList.add(new QueryParam(field, intList, PARAM_IN));
        return this;
    }


    /**
     * 添加in查询
     *
     * @field 是bean里头的属性, 不是db中的字段哦 !
     */
    public Query addIn(String field, Integer... objects) {
        if (objects == null || objects.length == 0) {
            return this;
        }

        List<Integer> list = new ArrayList<Integer>();
        Collections.addAll(list, objects);
        paramList.add(new QueryParam(field, list, PARAM_IN));
        return this;
    }


    /**
     * 添加范围查询
     *
     * @param fieldName
     * @param begin
     * @param end
     */
    public Query addBetween(String fieldName, Long begin, Long end) {
        if (begin == null && end == null) {
            return this;
        }

        if (begin != null && end == null) {
            paramList.add(new QueryParam(fieldName, begin - 1, PARAM_GT));
        } else if (begin == null) {
            paramList.add(new QueryParam(fieldName, end + 1, PARAM_LT));
        } else {
            if (begin > end) {
                return this;
            }
            paramList.add(new QueryParam(fieldName, new Between(begin, end), PARAM_BETWEEN));
        }
        return this;
    }

    /**
     * 添加范围查询
     *
     * @param fieldName
     * @param begin
     * @param end
     */
    public Query addBetween(String fieldName, Integer begin, Integer end) {
        if (begin == null && end == null) {
            return this;
        }

        if (begin != null && end == null) {
            paramList.add(new QueryParam(fieldName, begin - 1, PARAM_GT));
        } else if (begin == null) {
            paramList.add(new QueryParam(fieldName, end + 1, PARAM_LT));
        } else {
            if (begin > end) {
                return this;
            }

            paramList.add(new QueryParam(fieldName, new Between(begin, end), PARAM_BETWEEN));
        }
        return this;
    }

    public Query addBetween(String fieldName, Date begin, Date end) {
        if (begin == null && end == null) {
            return this;
        }

        if (begin != null && end == null) {
            paramList.add(new QueryParam(fieldName, begin, PARAM_GT));
        } else if (begin == null) {
            paramList.add(new QueryParam(fieldName, end, PARAM_LT));
        } else {
            if (begin.after(end)) {
                return this;
            }
            paramList.add(new QueryParam(fieldName, new Between(begin, end), PARAM_BETWEEN));
        }


        return this;
    }

    /**
     * 添加相等条件的语句
     *
     * @param fieldName
     * @param value
     */
    public Query addEq(String fieldName, Object value) {
        if (value == null) {
            return this;
        }
        paramList.add(new QueryParam(fieldName, value, PARAM_EQ));
        return this;
    }
    /**
     * 添加相等条件的语句
     *
     * @param fieldName
     * @param value
     */
    public Query addNotEq(String fieldName, Object value) {
        if (value == null) {
            return this;
        }
        paramList.add(new QueryParam(fieldName, value, PARAM_NOT_EQ));
        return this;
    }
    /**
     * 大于
     *
     * @param fieldName
     * @param value
     * @return
     */
    public Query addGt(String fieldName, Object value) {
        if (value == null) {
            return this;
        }
        paramList.add(new QueryParam(fieldName, value, PARAM_GT));
        return this;
    }

    /**
     * 小于
     *
     * @param fieldName
     * @param value
     * @return
     */
    public Query addLt(String fieldName, Object value) {
        if (value == null) {
            return this;
        }
        paramList.add(new QueryParam(fieldName, value, PARAM_LT));
        return this;
    }


    /**
     * 添加字段的模式匹配,模式匹配的%,_需要自己加
     *
     * @param fieldName
     * @param value
     */
    public Query addLike(String fieldName, String value) {
        if (StringUtils.isEmpty(value)) {
            return this;
        }

        StringBuilder sb = new StringBuilder();
        for (char c : value.toCharArray()) {
            String mysqlChar = MYSQL_SPECIAL_STR.get(c + "");
            if (mysqlChar != null) {
                sb.append(mysqlChar);
            } else {
                sb.append(c);
            }
        }

        paramList.add(new QueryParam(fieldName, "%" + sb.toString() + "%", PARAM_LIKE));
        return this;
    }

    /**
     * 添加字段的前缀匹配
     *
     * @param fieldName
     * @param value
     */
    public Query addPrefixLike(String fieldName, String value) {
        if (StringUtils.isEmpty(value)) {
            return this;
        }

        StringBuilder sb = new StringBuilder();
        for (char c : value.toCharArray()) {
            String mysqlChar = MYSQL_SPECIAL_STR.get(c + "");
            if (mysqlChar != null) {
                sb.append(mysqlChar);
            } else {
                sb.append(c);
            }
        }


        paramList.add(new QueryParam(fieldName, sb.toString() + "%", PARAM_LIKE));
        return this;
    }

    /**
     * 添加显示的字段,如果inculdeField为空则查询全部
     *
     * @param fieldName
     */
    public Query addIncludeField(String fieldName) {
        this.includeField.add(fieldName);
        return this;
    }

    /**
     * 包含字段
     *
     * @param fieldNames
     * @return
     */
    public Query addIncludeField(String... fieldNames) {
        Collections.addAll(this.includeField, fieldNames);
        return this;
    }

    /**
     * 设置分页
     *
     * @param pageNo
     * @param pageSize
     */
    public Query setPaged(int pageNo, int pageSize) {
        if (pageNo == 0) {
            pageNo = 1;
        }
        if (pageSize == 0) {
            pageSize = 10;
        }

        this.pageNo = pageNo;
        this.pageSize = pageSize;
        return this;
    }

    /**
     * 添加排序
     *
     * @param name
     * @param dbOrder
     */
    public Query addOrder(String name, DBOrder dbOrder) {
        this.orders.put(name, dbOrder);
        return this;
    }

    public boolean hasOrder() {
        return this.orders.size() > 0;
    }


    public Class<T> getType() {
        return type;
    }


    public Integer getPageNo() {
        return pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }


    public int getOffset() {
        if (pageNo == null || pageSize == null) {
            return -1;
        }

        return (pageNo - 1) * pageSize;
    }


    /**
     * 设置要查询的字段
     *
     * @return
     */
    public List<String> getIncludeField() {
        return includeField;
    }

    /**
     * 是否查询所有参数
     *
     * @return
     */
    public boolean isSearchAllField() {
        return includeField.isEmpty();
    }

    /**
     * 字段是否需要放入查询条件
     *
     * @return
     */
    public boolean isFieldSearch(String fieldName) {
        return includeField.contains(fieldName);
    }

    public static Query build(Class<?> clazz) {
        return new Query(clazz);
    }

    public Map<String, DBOrder> getOrders() {
        return orders;
    }




    public static class Between implements Serializable {
        Object begin;
        Object end;


        public Between(Object begin, Object end) {
            this.begin = begin;
            this.end = end;
        }

        public Object getBegin() {
            return begin;
        }


        public Object getEnd() {
            return end;
        }


    }

    public static enum DBOrder implements Serializable {
        DESC("DESC"), ASC("ASC");

        private DBOrder(String name) {
            this.name = name;
        }

        String name;

        public String getName() {
            return name;
        }
    }

    public static class QueryInParam<E> implements Serializable {
        private List<E> list = new ArrayList<E>();

        public QueryInParam(Collection<? extends E> c) {
            list.addAll(c);
        }

        public QueryInParam(E[] objects) {
            Collections.addAll(list, objects);
        }


        public String getArrayStr() {
            StringBuilder sb = new StringBuilder();
            for (Object obj : list) {
                sb.append(obj.toString()).append(",");
            }

            return sb.substring(0, sb.length() - 1);
        }
    }


    public List<QueryParam> getParamList() {
        return paramList;
    }
}
